<template>
  <el-dialog
    v-model="visible"
    title="编辑个人信息"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="头像">
        <div class="avatar-edit">
          <up-load-img v-model="form.avatar" action="/api/file/upload" />
        </div>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="form.name" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="公司">
        <el-input v-model="form.company" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="地置">
        <el-input v-model="form.location" placeholder="请输入公司地址" />
      </el-form-item>
      <el-form-item label="个人简介">
        <el-input v-model="form.bio" type="textarea" placeholder="请输入个人简介" />
      </el-form-item>
      <el-form-item label="个人网站">
        <el-input v-model="form.website" placeholder="请输入个人网站" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, inject } from 'vue';
import { ElMessage } from 'element-plus';
import * as authApi from '@/api/auth';
import UpLoadImg from '@/components/common/upLoadImg.vue';

const props = defineProps<{
  visible: boolean;
  user: {
    id: number;
    name: string;
    avatar?: string;
    profile: {
      company?: string;
      bio?: string;
      location?: string;
      website?: string;
    };
  };
}>();
const getUser = inject<() => void>('getUser');
const emit = defineEmits(['update:visible']);

const visible = ref(props.visible);
watch(
  () => props.visible,
  (val) => (visible.value = val)
);

const form = ref({
  avatar: props.user.avatar || '',
  name: props.user.name || '',
  company: props.user.profile?.company || '',
  bio: props.user.profile?.bio || '',
  location: props.user.profile?.location || '',
  website: props.user.profile?.website || ''
});

// 编辑弹窗关闭
function handleClose() {
  emit('update:visible', false);
}

// 编辑弹窗确定
async function handleConfirm() {
  try {
    // 构造要提交的数据
    const updateData = {
      avatar: form.value.avatar,
      name: form.value.name,
      profile: {
        company: form.value.company,
        bio: form.value.bio,
        location: form.value.location,
        website: form.value.website
      }
    };
    // 调用接口
    await authApi.profileUserInfo(updateData);
    //  刷新用户信息
    getUser && getUser();
    ElMessage.success('个人信息修改成功');
    emit('update:visible', false);
  } catch (error) {
    ElMessage.error('修改失败');
    console.error(error);
  }
}
</script>

<style scoped lang="scss">
.avatar-edit {
  display: flex;
  align-items: center;
  gap: 16px;
}
</style>
